import json, base64, pickle
from django import http
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection

from goods.models import SKU
from meiduo_mall.utils.response_code import RETCODE


class CartsView(View):
    """购物车管理"""
    # 添加购物车
    def post(self, request):
        """保存购物车"""

        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)  # 可选（无值时为True）

        # 校验参数
        if not all([sku_id, count]):
            return http.HttpResponseForbidden('缺少必传参数')

        # 校验sku_id是否合法
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('参数sku_id有误')

        # 校验count是否数字
        try:
            count = int(count)
        except Exception as e:
            return http.HttpResponseForbidden('参数count有误')

        #  校验勾选是否是bool
        if selected:
            # 判断是否bool类型
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')

        # 判断用户是否登录
        user = request.user
        # 认证用户
        if user.is_authenticated:
            # 用户登录，操作redis购物车
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            # 以增量计算的形式保存数据
            pl.hincrby('carts_%s' % user.id, sku_id, count)
            # 保存商品勾选状态
            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)
            # 执行
            pl.execute()

            return http.JsonResponse({"code": RETCODE.OK, 'errmsg': 'OK'})
        else:
            # 用户未登录
            # 获取cookie中的购物车数据，并判断是否有购物车数据
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 转二进制
                cart_str_bytes = cart_str.encode()
                # 转byte字典
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                # 转真字典
                cart_dict = pickle.loads(cart_dict_bytes)
            else:
                cart_dict = {}

            # 判断当前要添加的商品在cart_dict中是否存在
            if sku_id in cart_dict:
                # 购物车已存在，增量计算
                origin_count = cart_dict[sku_id]['count']
                count += origin_count

            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }
            # 转bytes字典
            cart_dict_bytes = pickle.dumps(cart_dict)
            # 转bytes字符串
            cart_str_bytes = base64.b64encode(cart_dict_bytes)
            # 转字符串
            cookie_cart_str = cart_str_bytes.decode()

            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})
            # 将cookie写入浏览器：reqponse.set_cookie('key', value)
            response.set_cookie('carts', cookie_cart_str)

            return response

    # 查询购物车
    def get(self, request):
        """查询购物车"""
        user = request.user
        if user.is_authenticated:
            # 登录用户
            redis_conn = get_redis_connection('carts')
            # 查询hash数据
            redis_cart = redis_conn.hgetall('carts_%s' % user.id)
            # 查询set数据
            redis_selected = redis_conn.smembers('selected_%s' % user.id)
            """
            {
                "sku_id1":{
                    "count":"1",
                    "selected":"True"
                },
                "sku_id2":{
                    "count":"2",
                    "selected":"True"
                },
            }
            """
            cart_dict = {}
            for sku_id, count in redis_cart.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in redis_selected
                }
        else:
            # 用户未登录，查询cookies购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_str_bytes = cart_str.encode()
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                cart_dict = pickle.loads(cart_dict_bytes)
            else:
                cart_dict = {}

        # 构造响应数据
        # 获取字典中所有的key-->sku_id
        sku_ids = cart_dict.keys()
        # 查询所有的skus
        skus = SKU.objects.filter(id__in=sku_ids)
        """
        {
            "sku_id1":{
                "count":"1",
                "selected":"True"
            },
            "sku_id2":{
                "count":"2",
                "selected":"True"
            },
        }
        """
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'count': cart_dict.get(sku.id).get('count'),
                'selected': str(cart_dict.get(sku.id).get('selected')),
                'name': sku.name,
                'price': str(sku.price),
                'amount': str(sku.price * cart_dict.get(sku.id).get('count')),
                'default_image_url': sku.default_image.url,
            })
        context = {
            'cart_skus': cart_skus
        }
        return render(request, 'cart.html', context)

    # 修改购物车
    def put(self, request):
        """修改购物车"""
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        if not all([sku_id, count]):
            return http.HttpResponseForbidden('缺少必传参数')

        # 判断sku_id是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品sku_id不存在')
        # 判断count是否数字
        try:
            count = int(count)
        except Exception:
            return http.HttpResponseForbidden('参数count有误')
        # 判断selected是否为bool类型
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')
        # 判断用户登录否
        user = request.user
        if user.is_authenticated:
            # 用户已登录
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            # 覆盖写入：hincrby()增量(新值加旧值)
            pl.hset('carts_%s' % user.id, sku_id, count)
            # 修改勾选状态
            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)
            else:
                pl.srem('selected_%s' % user.id, sku_id)
            pl.execute()

            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'price': sku.price,
                'amount': sku.price * count,
                'default_image_url': sku.default_image.url,
            }
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'cart_sku': cart_sku})
        else:
            # 用户未登录,修改cookie购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_str_bytes = cart_str.encode()
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                cart_dict = pickle.loads(cart_dict_bytes)
            else:
                cart_dict = {}

            # 覆盖写入
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }

            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'price': sku.price,
                'amount': sku.price * count,
                'default_image_url': sku.default_image.url
            }

            cart_dict_bytes = pickle.dumps(cart_dict)
            cart_str_bytes = base64.b64encode(cart_dict_bytes)
            cookie_cart_str = cart_str_bytes.decode()

            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'cart_sku': cart_sku})
            # 将新数据写入cookie：
            response.set_cookie('carts')
            return response

    # 删除购物车
    def delete(self, request):
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')

        # 判断sku_id是否存在
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExsit:
            return http.HttpResponseForbidden('商品不存在')

        # 判断用户是否登录
        user = request.user
        if user is not None and user.is_authenticated:
            # 用户已登录,删除redis购物车
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            # 删除hash购物车数据
            pl.hdel('carts_%s' % user.id, sku_id)
            # 删除勾选
            pl.srem('selected_%s' % user.id, sku_id)
            pl.execute()

            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})

        else:
            # 用户未登录
            # 获取cookie购物车数据
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_str_bytes = cart_str.encode()
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                cart_dict = pickle.loads(cart_dict_bytes)
            else:
                cart_dict = {}

            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})

            # 删除字典指定key所对应的记录
            if sku_id in cart_dict:
                # 若key不存在，会抛出异常
                del cart_dict[sku_id]

                cart_dict_bytes = pickle.dumps(cart_dict)
                cart_str_bytes = base64.b64encode(cart_dict_bytes)
                cookie_cart_str = cart_str_bytes.decode()

                response.set_cookie('carts', cookie_cart_str)

            return response


class CartsSelectAllView(View):
    """全选购物车"""
    def put(self, request):
        """保存购物车"""
        #  接收参数
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected', True)

        # 校验参数
        if selected:
            #  判断是否布尔类型
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')

        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 已登录，操作redis购物车
            redis_conn = get_redis_connection('carts')

            # 获取所有记录
            redis_cart = redis_conn.hgetall('carts_%s' % user.id)
            # 获取字典中所有的key
            redis_sku_ids = redis_cart.keys()
            # 判断用户是否全选
            if selected:
                # 全选
                redis_conn.sadd('selected_%s' % user.id, *redis_sku_ids)
            else:
                # 取消全选
                redis_conn.srem('selected_%s' % user.id, *redis_sku_ids)

            return http.JsonResponse({"code": RETCODE.OK, 'errmsg': 'OK'})
        else:
            # 用户未登录，操作cookie购物车
            # 获取cookie数据，并判断是否有购物车数据
            cart_str = request.COOKIES.get('carts')

            response = http.JsonResponse({"code": RETCODE.OK, 'errmsg': 'OK'})

            if cart_str:
                # 转二进制
                cart_str_bytes = cart_str.encode()
                # 转byte字典
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                # 转真字典
                cart_dict = pickle.loads(cart_dict_bytes)

                # 遍历购物车数据
                for sku_id in cart_dict:
                    cart_dict[sku_id]['selected'] = selected

                # 转bytes字典
                cart_dict_bytes = pickle.dump(cart_dict)
                # 转bytes字符串
                cart_str_bytes = base64.b64encode(cart_dict_bytes)
                # 转字符串
                cookie_cart_str = cart_str_bytes.decode()

                response.set_cookie('cart', cookie_cart_str)

            return response

